<?php
/**
 * Created by PhpStorm.
 * User: yuyj
 * Date: 2016-03-03
 * Time: 14:41
 */

namespace common\components\aliyun;

include_once __DIR__ . '/../../../vendor/aliyun-openapi-php-sdk/aliyun-php-sdk-core/Config.php';

use common\repositories\config\ConfigSettingRepository;
use common\support\ServiceHelper;
use Rds\Request\V20140815 as BaseRds;
use DefaultAcsClient;
use DefaultProfile;
use Yii;
use yii\base\Component;
use yii\base\Exception;

class Rds extends Component
{
    public $accessKey;
    public $accessSecret;
    public $regionId;
    public $accountName;

    public static $client;

    public function __construct($config = [])
    {
        parent::__construct($config);

        //从数据库读取配置
        $this->accessKey = $this->_getConfigByKey('ACCESS_KEY_ID');
        $this->accessSecret = $this->_getConfigByKey('ACCESS_KEY_SECRET');
        $this->regionId = $this->_getConfigByKey('RDS_REGION_ID');
        $this->accountName = $this->_getConfigByKey('RDS_ACCOUNT_NAME');

        if (self::$client === null) {
            $iClientProfile = DefaultProfile::getProfile($this->regionId, $this->accessKey, $this->accessSecret);
            self::$client = new DefaultAcsClient($iClientProfile);
        }
    }

    private function _getConfigByKey($key)
    {
        $configSettingRepository = new ConfigSettingRepository();
        $config = $configSettingRepository->getByKey($key);
        if(empty($config)){
            throw new Exception('找不到配置项：'.$key);
        }
        $config = $config->toArray();
        return $config['Value'];
    }

    public function __call($name, $arguments)
    {
        if ($arguments && !is_array($arguments[0])) {
            throw new Exception('参数必须是一个数组');
        }

        $class = sprintf('Rds\Request\V20140815\%sRequest', ucfirst($name));

        $request = Yii::createObject($class);
        $request->setMethod("GET");

        foreach ($arguments[0] as $property => $value) {
            $method = 'set' . $property;
            $request->$method($value);
        }

        $response = self::$client->getAcsResponse($request);

        if (isset($response->Code)) {
            throw new Exception($response->Message, $response->Code);
        } else {
            return $response;
        }
    }

    public function GrantAccountPrivilege(array $arguments)
    {
        $arguments['AccountName'] = $this->accountName;

        return $this->__call(__FUNCTION__, [$arguments]);
    }
}
